<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
    <title>管理图书</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 自定义Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#f97316',
                        movie: '#3b82f6',
                        book: '#10b981',
                        neutral: {
                            100: '#f3f4f6',
                            200: '#e5e7eb',
                            700: '#374151',
                            800: '#1f2937',
                            900: '#111827'
                        }
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .btn-hover {
                @apply transition-all duration-300 hover:shadow-lg hover:-translate-y-0.5;
            }
            .form-input-focus {
                @apply focus:ring-2 focus:ring-book/50 focus:border-book;
            }
            .nav-active {
                @apply text-primary border-b-2 border-book pb-0.5 font-medium;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans">
<!-- 导航栏 -->
<nav class="bg-white shadow-md sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-6">
            <a href="<%= request.getContextPath() %>/cjj/admin_dashboard.jsp" class="text-primary font-medium flex items-center">
                <i class="fa fa-tachometer mr-2"></i> 管理后台
            </a>
            <a href="<%= request.getContextPath() %>/cjj/admin_dashboard.jsp" class="text-neutral-700 hover:text-primary transition-colors ${activePage == 'dashboard' ? 'nav-active' : ''}">
                <i class="fa fa-home mr-1"></i> 首页
            </a>
            <div class="relative group ${activePage == 'movies' ? '' : (activePage == 'books' ? 'nav-active' : '')}">
                <a href="#" class="nav-link text-neutral-700 hover:text-primary transition-colors flex items-center" data-page="movies">
                    <i class="fa fa-film mr-1"></i> 电影管理 <i class="fa fa-chevron-down ml-1 text-xs"></i>
                </a>
                <div id="movieDropdown" class="absolute left-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10 hidden group-hover:block pointer-events-auto">
                    <a href="<%= request.getContextPath() %>/cjj/publish_movie.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-movie hover:text-white">发布电影</a>
                    <a href="<%= request.getContextPath() %>/cjj/manage_movies.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-movie hover:text-white">管理电影</a>
                </div>
            </div>
            <div class="relative group ${activePage == 'books' ? 'nav-active' : ''}">
                <a href="#" class="nav-link text-primary border-b-2 border-book pb-0.5 font-medium flex items-center" data-page="books">
                    <i class="fa fa-book mr-1"></i> 图书管理 <i class="fa fa-chevron-down ml-1 text-xs"></i>
                </a>
                <div id="bookDropdown" class="absolute left-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10 hidden group-hover:block pointer-events-auto">
                    <a href="<%= request.getContextPath() %>/cjj/publish_book.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-book hover:text-white">发布图书</a>
                    <a href="<%= request.getContextPath() %>/cjj/manage_books.jsp" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-book hover:text-white">管理图书</a>
                </div>
            </div>
            <a href="<%= request.getContextPath() %>/cjj/manage_admins.jsp" class="text-neutral-700 hover:text-primary transition-colors ${activePage == 'admins' ? 'nav-active' : ''}">
                <i class="fa fa-users mr-1"></i> 管理管理员
            </a>
        </div>
        <div class="flex items-center space-x-4">
                <span class="text-neutral-700">
                    <i class="fa fa-user-circle mr-1"></i>
                    <%= (String)request.getSession().getAttribute("adminUsername") != null
                            ? (String)request.getSession().getAttribute("adminUsername") : "管理员" %>
                </span>
            <a href="<%= request.getContextPath() %>/admin/logout" class="text-neutral-700 hover:text-red-500 transition-colors">
                <i class="fa fa-sign-out mr-1"></i> 退出
            </a>
        </div>
    </div>
</nav>

<!-- 主内容区 -->
<main class="container mx-auto px-4 py-8">
    <!-- 页面标题 -->
    <div class="bg-gradient-to-r from-book/10 to-book/5 rounded-xl p-6 mb-8">
        <h1 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold text-neutral-800">管理图书</h1>
        <p class="text-neutral-600 mt-2">查看和管理所有图书信息</p>
    </div>

    <!-- 操作结果提示 -->
    <%
        String message = (String) request.getAttribute("message");
        boolean success = request.getAttribute("success") != null &&
                (Boolean) request.getAttribute("success");
        if (message != null) {
    %>
    <div class="mb-4 px-4 py-3 rounded-lg
        <%= success ? "bg-green-50 border border-green-200 text-green-700" :
                      "bg-red-50 border border-red-200 text-red-700" %>">
        <div class="flex items-center">
            <i class="fa fa-<%= success ? "check-circle" : "exclamation-circle" %> mr-2"></i>
            <span><%= message %></span>
        </div>
    </div>
    <%
        }
    %>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-xl p-6 card-shadow mb-8">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
            <div>
                <div class="relative">
                    <input type="text" placeholder="搜索图书..." class="w-full pl-10 pr-4 py-2 border border-neutral-300 rounded-lg form-input-focus">
                    <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400"></i>
                </div>
            </div>
            <div>
                <select class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus">
                    <option value="">所有分类</option>
                    <option value="literature">文学</option>
                    <option value="history">历史</option>
                    <option value="science">科学</option>
                    <option value="technology">技术</option>
                    <option value="philosophy">哲学</option>
                    <option value="art">艺术</option>
                    <option value="life">生活</option>
                </select>
            </div>
            <div>
                <select class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus">
                    <option value="">所有状态</option>
                    <option value="active">上架</option>
                    <option value="inactive">下架</option>
                </select>
            </div>
        </div>

        <div class="flex justify-end mb-4">
            <a href="<%= request.getContextPath() %>/cjj/publish_book.jsp" class="px-5 py-2.5 bg-book text-white rounded-lg hover:bg-book/90 transition-colors btn-hover">
                <i class="fa fa-plus-circle mr-2"></i> 发布图书
            </a>
        </div>

        <!-- 图书表格 -->
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-neutral-200">
                <thead class="bg-neutral-50">
                <tr>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">ID</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">封面</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">标题</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">作者</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">分类</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">出版年份</th>
                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-neutral-500 uppercase tracking-wider">状态</th>
                    <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-neutral-500 uppercase tracking-wider">操作</th>
                </tr>
                </thead>
                <tbody class="bg-white divide-y divide-neutral-200">
                <%
                    // 处理删除操作
                    String action = request.getParameter("action");
                    if ("delete".equals(action) && request.getParameter("bookId") != null) {
                        try {
                            Integer bookId = Integer.valueOf(request.getParameter("bookId"));
                            Connection conn = null;
                            PreparedStatement stmt = null;

                            try {
                                // 设置数据库连接编码
                                Class.forName("com.mysql.cj.jdbc.Driver");
                                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8", "root", "root");

                                // 执行删除操作
                                String sql = "DELETE FROM book WHERE BOOK_ID = ?";
                                stmt = conn.prepareStatement(sql);
                                stmt.setInt(1, bookId);
                                int rows = stmt.executeUpdate();

                                if (rows > 0) {
                                    request.setAttribute("message", "图书删除成功");
                                    request.setAttribute("success", true);
                                } else {
                                    request.setAttribute("message", "未找到指定图书");
                                    request.setAttribute("success", false);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                request.setAttribute("message", "删除图书失败: " + e.getMessage());
                                request.setAttribute("success", false);
                            } finally {
                                try { if (stmt != null) stmt.close(); } catch (SQLException e) {}
                                try { if (conn != null) conn.close(); } catch (SQLException e) {}
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            request.setAttribute("message", "参数错误: " + e.getMessage());
                            request.setAttribute("success", false);
                        }
                    }

                    // 处理编辑操作
                    if ("edit".equals(action) && request.getParameter("bookId") != null) {
                        try {
                            Integer bookId = Integer.valueOf(request.getParameter("bookId"));
                            String title = request.getParameter("title");
                            String author = request.getParameter("author");
                            String category = request.getParameter("category");
                            String publishYearStr = request.getParameter("publishYear");
                            String status = request.getParameter("status");

                            Connection conn = null;
                            PreparedStatement stmt = null;

                            try {
                                // 设置数据库连接编码
                                Class.forName("com.mysql.cj.jdbc.Driver");
                                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8", "root", "root");

                                // 执行更新操作
                                String sql = "UPDATE book SET TITLE=?, AUTHOR=?, CATEGORY=?, PUBLISH_YEAR=?, STATUS=? WHERE BOOK_ID=?";
                                stmt = conn.prepareStatement(sql);
                                stmt.setString(1, title);
                                stmt.setString(2, author);
                                stmt.setString(3, category);
                                stmt.setObject(4, publishYearStr.isEmpty() ? null : Integer.valueOf(publishYearStr));
                                stmt.setString(5, status);
                                stmt.setInt(6, bookId);

                                int rows = stmt.executeUpdate();

                                if (rows > 0) {
                                    request.setAttribute("message", "图书更新成功");
                                    request.setAttribute("success", true);
                                } else {
                                    request.setAttribute("message", "未找到指定图书");
                                    request.setAttribute("success", false);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                request.setAttribute("message", "更新图书失败: " + e.getMessage());
                                request.setAttribute("success", false);
                            } finally {
                                try { if (stmt != null) stmt.close(); } catch (SQLException e) {}
                                try { if (conn != null) conn.close(); } catch (SQLException e) {}
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            request.setAttribute("message", "参数错误: " + e.getMessage());
                            request.setAttribute("success", false);
                        }
                    }

                    // 查询图书列表
                    List<Map<String, Object>> books = new ArrayList<>();
                    Connection conn = null;
                    Statement stmt = null;
                    ResultSet rs = null;

                    try {
                        // 设置数据库连接编码
                        Class.forName("com.mysql.cj.jdbc.Driver");
                        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webproject_2025?useUnicode=true&characterEncoding=UTF-8", "root", "root");
                        stmt = conn.createStatement();
                        rs = stmt.executeQuery("SELECT BOOK_ID, TITLE, AUTHOR, CATEGORY, PUBLISH_YEAR, STATUS, COVER_IMAGE FROM book");

                        while (rs.next()) {
                            Map<String, Object> book = new HashMap<>();
                            book.put("id", rs.getInt("BOOK_ID"));
                            book.put("title", rs.getString("TITLE"));
                            book.put("author", rs.getString("AUTHOR"));
                            book.put("category", rs.getString("CATEGORY"));
                            book.put("publishYear", rs.getObject("PUBLISH_YEAR"));
                            book.put("status", rs.getString("STATUS"));
                            book.put("coverImage", rs.getString("COVER_IMAGE"));
                            books.add(book);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                %>
                <tr>
                    <td colspan="8" class="px-6 py-4 text-center text-red-500">
                        数据库查询失败: <%= e.getMessage() %>
                    </td>
                </tr>
                <%
                    } finally {
                        try { if (rs != null) rs.close(); } catch (SQLException e) {}
                        try { if (stmt != null) stmt.close(); } catch (SQLException e) {}
                        try { if (conn != null) conn.close(); } catch (SQLException e) {}
                    }

                    // 动态生成表格行
                    if (books.isEmpty()) {
                %>
                <tr>
                    <td colspan="8" class="px-6 py-4 text-center text-neutral-500">
                        没有找到图书记录
                    </td>
                </tr>
                <%
                } else {
                    for (Map<String, Object> book : books) {
                        // 获取并处理可能为null的值
                        Object publishYearObj = book.get("publishYear");
                        String publishYearStr = publishYearObj != null ? publishYearObj.toString() : "未知";
                        String status = (String) book.get("status");
                %>
                <tr>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-500"><%= book.get("id") %></td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <img src="<%= book.get("coverImage") != null ? book.get("coverImage") : "https://picsum.photos/seed/book/60/90" %>"
                             alt="图书封面" class="w-12 h-18 object-cover rounded">
                    </td>
                    <td class="px-6 py-4 text-sm font-medium text-neutral-900"><%= book.get("title") %></td>
                    <td class="px-6 py-4 text-sm text-neutral-700"><%= book.get("author") %></td>
                    <td class="px-6 py-4 text-sm text-neutral-700"><%= book.get("category") != null ? book.get("category") : "未分类" %></td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-neutral-700"><%= publishYearStr %></td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <% if ("active".equals(status)) { %>
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">上架</span>
                        <% } else if ("inactive".equals(status)) { %>
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">下架</span>
                        <% } else { %>
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800"><%= status != null ? status : "未知" %></span>
                        <% } %>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button onclick="editBook(
                            <%= book.get("id") %>,
                                '<%= book.get("title") != null ? ((String) book.get("title")).replace("'", "\\'") : "" %>',
                                '<%= book.get("author") != null ? ((String) book.get("author")).replace("'", "\\'") : "" %>',
                                '<%= book.get("category") != null ? ((String) book.get("category")).replace("'", "\\'") : "" %>',
                                '<%= publishYearStr %>',
                                '<%= status %>',
                                '<%= book.get("coverImage") != null ? ((String) book.get("coverImage")).replace("'", "\\'") : "" %>'
                                )" class="text-primary hover:text-primary/80 mr-3">编辑</button>
                        <button onclick="deleteBook(<%= book.get("id") %>)" class="text-red-500 hover:text-red-600">删除</button>
                    </td>
                </tr>
                <%
                        }
                    }
                %>
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        <div class="flex justify-between items-center mt-6">
            <div class="text-sm text-neutral-500">
                显示 1 到 <%= books.size() %> 条，共 <%= books.size() %> 条记录
            </div>
            <div class="flex space-x-2">
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">上一页</a>
                <a href="#" class="px-3 py-1 bg-book text-white rounded-md hover:bg-book/90">1</a>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">2</a>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">3</a>
                <span class="px-3 py-1 text-neutral-500">...</span>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">86</a>
                <a href="#" class="px-3 py-1 border border-neutral-300 rounded-md text-neutral-700 hover:bg-neutral-50">下一页</a>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-white border-t border-neutral-200 py-6">
    <div class="container mx-auto px-4">
        <div class="flex flex-col md:flex-row justify-between items-center">
            <div class="text-neutral-600 text-sm mb-4 md:mb-0">
                © 2025 影视图书管理系统. 保留所有权利.
            </div>
            <div class="flex space-x-4">
                <a href="#" class="text-neutral-600 hover:text-primary transition-colors">
                    <i class="fa fa-question-circle mr-1"></i> 帮助中心
                </a>
                <a href="#" class="text-neutral-600 hover:text-primary transition-colors">
                    <i class="fa fa-envelope mr-1"></i> 联系我们
                </a>
                <a href="#" class="text-neutral-600 hover:text-primary transition-colors">
                    <i class="fa fa-file-text-o mr-1"></i> 使用条款
                </a>
            </div>
        </div>
    </div>
</footer>

<!-- 编辑图书模态框 -->
<div id="editBookModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-neutral-800">编辑图书</h3>
            <button onclick="closeEditModal()" class="text-neutral-400 hover:text-neutral-600">
                <i class="fa fa-times"></i>
            </button>
        </div>
        <form id="editBookForm" method="post" action="<%= request.getContextPath() %>/cjj/manage_books.jsp">
            <input type="hidden" name="action" value="edit">
            <input type="hidden" id="editBookId" name="bookId">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="editTitle" class="block text-sm font-medium text-neutral-700 mb-1">标题</label>
                    <input type="text" id="editTitle" name="title" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                </div>
                <div>
                    <label for="editAuthor" class="block text-sm font-medium text-neutral-700 mb-1">作者</label>
                    <input type="text" id="editAuthor" name="author" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                </div>
                <div>
                    <label for="editCategory" class="block text-sm font-medium text-neutral-700 mb-1">分类</label>
                    <select id="editCategory" name="category" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                        <option value="literature">文学</option>
                        <option value="history">历史</option>
                        <option value="science">科学</option>
                        <option value="technology">技术</option>
                        <option value="philosophy">哲学</option>
                        <option value="art">艺术</option>
                        <option value="life">生活</option>
                    </select>
                </div>
                <div>
                    <label for="editPublishYear" class="block text-sm font-medium text-neutral-700 mb-1">出版年份</label>
                    <input type="number" id="editPublishYear" name="publishYear" min="1000" max="9999"
                           class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus">
                </div>
                <div>
                    <label for="editStatus" class="block text-sm font-medium text-neutral-700 mb-1">状态</label>
                    <select id="editStatus" name="status" class="w-full px-4 py-2 border border-neutral-300 rounded-lg form-input-focus" required>
                        <option value="active">上架</option>
                        <option value="inactive">下架</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-neutral-700 mb-1">封面图片</label>
                    <div class="mb-2">
                        <img id="editCoverPreview" src="https://picsum.photos/seed/book/128/192" alt="图书封面预览" class="w-32 h-48 object-cover rounded">
                    </div>
                    <input type="file" name="coverImage" accept="image/*" class="w-full text-sm text-neutral-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-medium file:bg-book file:text-white hover:file:bg-book/90">
                </div>
            </div>
            <div class="mt-6 flex justify-end space-x-3">
                <button type="button" onclick="closeEditModal()" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-50 transition-colors">取消</button>
                <button type="submit" class="px-5 py-2.5 bg-book text-white rounded-lg hover:bg-book/90 transition-colors btn-hover">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 w-full max-w-md">
        <div class="text-center mb-4">
            <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100 text-red-500 mb-4">
                <i class="fa fa-trash-o text-2xl"></i>
            </div>
            <h3 class="text-lg font-semibold text-neutral-800">确认删除</h3>
            <p class="text-neutral-600 mt-2">确定要删除这本书吗？此操作不可撤销。</p>
        </div>
        <div class="flex justify-center space-x-3 mt-6">
            <button onclick="closeDeleteModal()" class="px-4 py-2 border border-neutral-300 rounded-lg text-neutral-700 hover:bg-neutral-50 transition-colors">取消</button>
            <button onclick="confirmDeleteBook()" class="px-5 py-2.5 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors btn-hover">确认删除</button>
        </div>
    </div>
</div>

<!-- JavaScript -->
<script>
    // 转义JavaScript字符串，防止引号问题
    function escapeJsString(str) {
        if (!str) return '';
        return str
            .replace(/\\/g, '\\\\')
            .replace(/'/g, '\\\'')
            .replace(/"/g, '\\"')
            .replace(/\n/g, '\\n')
            .replace(/\r/g, '\\r')
            .replace(/\t/g, '\\t');
    }

    document.addEventListener('DOMContentLoaded', function() {
        console.log('Manage Books Page Loaded');
        // 设置当前页面为图书管理
        document.querySelector('[data-page="books"]').parentElement.classList.add('nav-active');

        // 导航栏下拉菜单优化
        const movieDropdown = document.getElementById('movieDropdown');
        const bookDropdown = document.getElementById('bookDropdown');
        const movieMenu = movieDropdown.parentElement;
        const bookMenu = bookDropdown.parentElement;

        // 鼠标离开菜单时添加延迟消失效果
        let hideTimeout;
        const dropdowns = [
            { menu: movieMenu, dropdown: movieDropdown },
            { menu: bookMenu, dropdown: bookDropdown }
        ];

        dropdowns.forEach(item => {
            const { menu, dropdown } = item;

            // 鼠标进入菜单或下拉框时显示下拉框
            menu.addEventListener('mouseenter', () => {
                clearTimeout(hideTimeout);
                dropdown.classList.remove('hidden');
            });

            // 鼠标离开菜单时延迟隐藏下拉框
            menu.addEventListener('mouseleave', () => {
                hideTimeout = setTimeout(() => {
                    dropdown.classList.add('hidden');
                }, 200);
            });

            // 鼠标进入下拉框时取消隐藏延迟
            dropdown.addEventListener('mouseenter', () => {
                clearTimeout(hideTimeout);
            });

            // 鼠标离开下拉框时重新设置隐藏延迟
            dropdown.addEventListener('mouseleave', () => {
                hideTimeout = setTimeout(() => {
                    dropdown.classList.add('hidden');
                }, 200);
            });
        });
    });

    // 当前要删除的图书ID
    let currentBookId = null;

    // 编辑图书函数
    function editBook(id, title, author, category, publishYear, status, coverImage) {
        // 处理可能的空值和转义
        title = title || '';
        author = author || '';
        category = category || '';
        publishYear = publishYear === '未知' ? '' : publishYear;
        status = status || 'active';
        coverImage = coverImage || 'https://picsum.photos/seed/book/128/192';

        document.getElementById('editBookId').value = id;
        document.getElementById('editTitle').value = title;
        document.getElementById('editAuthor').value = author;
        document.getElementById('editCategory').value = category;
        document.getElementById('editPublishYear').value = publishYear;
        document.getElementById('editStatus').value = status;
        document.getElementById('editCoverPreview').src = coverImage;

        document.getElementById('editBookModal').classList.remove('hidden');
    }

    // 关闭编辑模态框
    function closeEditModal() {
        document.getElementById('editBookModal').classList.add('hidden');
        document.getElementById('editBookForm').reset();
    }

    // 删除图书函数
    function deleteBook(id) {
        currentBookId = id;
        document.getElementById('deleteModal').classList.remove('hidden');
    }

    // 关闭删除确认模态框
    function closeDeleteModal() {
        currentBookId = null;
        document.getElementById('deleteModal').classList.add('hidden');
    }

    // 确认删除图书
    function confirmDeleteBook() {
        if (currentBookId) {
            // 使用表单提交而不是直接跳转，以防止GET请求长度限制
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '<%= request.getContextPath() %>/cjj/manage_books.jsp';

            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = 'delete';

            const bookIdInput = document.createElement('input');
            bookIdInput.type = 'hidden';
            bookIdInput.name = 'bookId';
            bookIdInput.value = currentBookId;

            form.appendChild(actionInput);
            form.appendChild(bookIdInput);
            document.body.appendChild(form);

            form.submit();
            document.body.removeChild(form);
        }
        closeDeleteModal();
    }
</script>
</body>
</html>